/**

supposed to ping a bunch of urls in the form of http://www.urlname.com,portno

I need to;

strip the http://
strip the www (if present)
strip and get just the urlname.tld and ignore the "," port number

NOTE : when used in UNIX systems, you will need to sudo, because ICMP ECHO REQUEST is privileged,
otherwise, isReachable returns false, even if it actually is reachable.

*/

import java.net.InetAddress;
import java.io.File;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.net.UnknownHostException;

class PingUtil {
	
	int timeout = 1000; //3 seconds is reasonable timeout value
	String port_delimeter = ","; //this is what separates the http url from the port number in the text file
	
	public static void main(String []args) {
		
		if(args.length == 0) {
			System.out.println("Usage : java PingUtil <yourfile.txt");
			System.exit(0);
		}
		
		PingUtil pu = new PingUtil();
		pu.process(args[0]);
		
	}	
	
// -----------------------------------------------------------------
	
	void process(String filename) {
	
		try {
			
			File file = new File(filename);
			FileInputStream fin = new FileInputStream(file);
			InputStreamReader in = new InputStreamReader(fin);
			BufferedReader bin = new BufferedReader(in);
			
			String line = "";
			
			System.out.println("Just press CTRL-C if you wanna stop ..");
			
			while ((line = bin.readLine()) != null) {

				String the_host = getJustTheHost(line);
				System.out.print(the_host + "  = ");
				System.out.println(ping(the_host));

			}
			
		}
		catch(FileNotFoundException fe) {
			fe.printStackTrace();
		}
		catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	String getJustTheHost(String url) {
		int comma_pos = url.lastIndexOf(",");
		return url.substring(11,comma_pos);
	}
	
	boolean ping(String host) {
		
		boolean retval = false;
		
		try {
			InetAddress addr = InetAddress.getByName(host);
			//System.out.println(addr);
			retval = addr.isReachable(timeout);
		}
		catch(UnknownHostException ue) {
			ue.printStackTrace();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		
		return retval;
	}
}